﻿using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Pay.Distribution.Controllers {
    /// <summary>
	/// 商品管理，开放所有商户可以使用
	/// </summary>
	public class ProductController : GeneralController {
        private IProductService _iProductService;
        private IGoodDeclarationService _iGoodDeclarationService;
        private IMerchantService _iMerchantService;
        private IDistributionProductService _iDistributionProductService;
        private ISettingService _settingService;
        public ProductController(IProductService iProductService, IGoodDeclarationService iGoodDeclarationServic, IMerchantService iMerchantService,
            IDistributionProductService iDistributionProductService, ISettingService settingService) {
            _iProductService = iProductService;
            _iGoodDeclarationService = iGoodDeclarationServic;
            _iMerchantService = iMerchantService;
            _iDistributionProductService = iDistributionProductService;
            _settingService = settingService;
        }

        [HttpGet]
        public JsonResult Gets(GoodsQuery query) {
            var merchant = _iMerchantService.Get(currentUser.user_id);
            if (merchant.is_oem)
                query.merchant_id = currentUser.user_id;
            else if (merchant.usertype == UserType.distributor)
                query.merchant_id = merchant.oem_id.Value;
            else
                query.sell_id = currentUser.user_id;
            if (merchant.usertype == UserType.distributor) {
                GoodsQuery good = new GoodsQuery() { sell_id = currentUser.user_id };
                var products = _iDistributionProductService.GetProducts(good);
                return Json(ResultToJson.Json(products), JsonRequestBehavior.AllowGet);
            }
            var result = _iProductService.GetForDistributionHt(query);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public async Task<JsonResult> Get(long id) {
            var product = _iProductService.Get(id);
            if (product.is_htl == 2) {
                product.product_skus.Clear();
                var sku_api = await _iProductService.SearchSkuInfo(product.sku);
                if (sku_api != null) {
                    product.product_skus.AddRange(sku_api.skus);
                    if (sku_api.skus.Count > 0)
                        product.cost_price = product.product_skus.Max(c => c.cost_price);
                    else {
                        product.stock = 0;
                    }
                }
            }
            return Json(ResultToJson.Json(product), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取申报商品记录
        /// </summary>
        [HttpGet]
        public JsonResult GetGoodsDeclarations(GoodDeclaQuery query) {
            query.bind_no = _iMerchantService.Get(currentUser.user_id).merchant_no;
            var result = _iGoodDeclarationService.GetGoodDeclarations(query);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存商品
        /// </summary>
        /// <returns>The save.</returns>
        /// <param name="model">Model.</param>
		[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
        [ValidateInput(false)]
        public JsonResult Save(product_model model) {
            var result = new ApiResultMessage { };
            var site = _settingService.Get().site;
            var merchant = _iMerchantService.Get(currentUser.user_id);
            var apiResult = UploadList("goods", merchant.merchant_no);
            if (apiResult != null)
                model.image_path = apiResult;
            List<string> tmp = new List<string>();
            if (apiResult != null) {
                foreach (var item in apiResult) {
                    tmp.Add(site.img_url + item);
                    if (tmp.Count > 0)
                        model.main_image_url = tmp[0];
                }
                model.image_path = tmp;
            }
            if (merchant.merchant_no == model.bind_no || model.bind_no == null)
                model.bind_no = merchant.merchant_no;
            if (string.IsNullOrEmpty(model.sku) || (!string.IsNullOrEmpty(model.sku) && model.sku == "null"))
                model.sku = string.Empty;
            if (model.good_dec_id > 0) {
                var validResult = _iGoodDeclarationService.VerifyGoodDeclaration(model.good_dec_id);
                if (!validResult)
                    return Json(ResultToJson.Json<string>("商品申报校验失败"));
            }
            if (model.is_htl == 2)
                result = _iProductService.SaveHniaoProduct(model);
            else
                result = _iProductService.Save(model);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpDelete]
        public JsonResult Delete(long id) {
            var result = _iProductService.Delete(id);
            return Json(ResultToJson.Json(result != 0 ? "删除成功" : "删除失败", result), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 上架/下架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Disable(long id) {
            var result = _iProductService.UpDown(id);
            return Json(ResultToJson.Json(result != 0 ? " 操作成功" : "操作失败", result), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
		///  商品审核
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
        [HttpPost]
        public JsonResult Audit(product_audit_req model) {
            var result = _iProductService.Audit(model.id, model.audit_status, model.audit_reason);
            return Json(ResultToJson.Json(result >= 0 ? " 操作成功" : "操作失败", result), JsonRequestBehavior.AllowGet);
        }
    }
}